package com.hegongda.okcmall.product.exception;

import com.hegongda.common.exception.ExceptionEnum;
import com.hegongda.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

/**
 *  进行全局异常处理
 * @author liueidong
 * @create 2021-02-09 20:49
 */
@RestControllerAdvice("com.hegongda.okcmall.product")  // 代表了@ResponseBody  和 @ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            fieldErrors.stream().forEach(item -> {
                String field = item.getField();
                String defaultMessage = item.getDefaultMessage();
                map.put(field, defaultMessage);
            });
        }
        return R.error(ExceptionEnum.VALID_EXCEPTION.getCode(),ExceptionEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }
}
